<?php
namespace app\user\controller;

use app\common\controller\Frontend;
use think\Session;
use think\Db;
use think\Config;
use app\common\model\User;
use app\common\model\Domain;
use app\common\model\Web;

class Index extends Frontend 
{

    public function index(){
        if($this->request->isAjax()){
            $data = $this->request->param();
            $total = $this->count($data['domain']??null);
            $today = $this->region($data['domain']??null);
            $this->success('',null,['total'=>$total,'today'=>'today']);
        }
        $total =$this->count();
        $today =$this->region();
        $this->assign('total',$total);
        $this->assign('today',$today);
        return $this->fetch();
    }
    protected function count($domain=0,$start=null,$end=null){
        $map['user_id'] = Session::get('spadminUser')['id'];
        if(empty($start) && empty($end)){
            $start = strtotime("-30 days");
            $end = strtotime(date("Y-m-d 23:59:59"));
        }else{
            $start = strtotime($start);
            $end = strtotime($end." 23:59:59");
        }
        $map['create_time'] = ['BETWEEN',[$start,$end]];
        if(!empty($domain)){
            $map['domain_id'] =$domain;
        }
       $sql = Db::name('BrowerLog')->where($map)->field(' DATE(FROM_UNIXTIME(`create_time`)) as `day`, count(`id`) as pv,count( DISTINCT `ip`) as uv ')->group('day')->select();
       $brower = array_column($sql,null,'day');
       $date = [];
       $pv = [];
       $uv = [];
       $sum = [];
       $i = 0;
       while (true) {
            $date[$i] = date('Y-m-d',$i*86400 + $start);
            $pv[$i] = $brower[$date[$i]]['pv']??0;
            $uv[$i] = $brower[$date[$i]]['uv']??0;
            if($pv[$i]>1){
                $map['create_time'] = ['BETWEEN',[strtotime($date[$i]),strtotime($date[$i])+86399]];
               $count = Db::name('BrowerLog')->where($map)->field('ip')->group('ip')->having('count(id)>1')->find();
                $sum[$i] = count($count);
            }else{
                $sum[$i] = $pv[$i];
            }
            if(strtotime($date[$i]) > $end){
                break;
            }else{
                $i++;
            }
       }
       return ['date'=>$date,'pv'=>$pv,'uv'=>$uv,'sum'=>$sum];
    }
    protected function region($domain=0,$time=null){
        $map['user_id'] = Session::get('spadminUser')['id'];
        if(empty($start) && empty($end)){
            $start = strtotime(date("Y-m-d"));
            $end = strtotime(date("Y-m-d 23:59:59"));
        }else{
            $start = strtotime($time);
            $end = strtotime($time." 23:59:59");
        }
        $map['create_time'] = ['BETWEEN',[$start,$end]];
        if(!empty($domain)){
            $map['domain_id'] =$domain;
        }
       $sql = Db::name('BrowerLog')->where($map)->field(' DATE_FORMAT(FROM_UNIXTIME(`create_time`),"%H") as `hour`, count(`id`) as pv,count( DISTINCT `ip`) as uv ')->group('hour')->select();
       $brower = array_column($sql,null,'hour');
       $date = [];
       $pv = [];
       $uv = [];
       $i = 0;
       while (true) {
            $date[$i] = $i<10?'0'.$i:$i;
            $pv[$i] = $brower[$date[$i]]['pv']??0;
            $uv[$i] = $brower[$date[$i]]['uv']??0;
            
            if($i == 23){
                break;
            }else{
                $i++;
            }
       }
       return ['date'=>$date,'pv'=>$pv,'uv'=>$uv];
    }
   
    public function form(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            if(empty($data['domain_id'])){
                if(empty(Session::get('domainId'))){
                    $this->error('未绑定短域名');
                }else{
                    $data['domain_id'] =Session::get('domainId');
                }
            }
            $data['url'] =urldecode($data['url']);
            if(filter_var($data['url'], FILTER_VALIDATE_URL) == false){
                $this->error('跳转链接编码错误');
            }
            $data['auto_click'] = $data['auto_click']??0;
            $data['area_type'] = $data['area_type']??0;
            $data['user_id'] = Session::get('userId');
            $result = model('Web')->allowField(true)->save($data,$data['id']?['id'=>$data['id']]:null);
            if($result === false){
                $this->error(model('Web')->getError());
            }
            $this->success('操作成功');
        }
        $id = $this->request->param('id');
        if(empty($id)){
            return $this->view->fetch('error');
        }
        $domain = Domain::where('id',$id)->where('user_id',Session::get('spadminUser')['id'])->find();
        if(empty($domain)){
            return $this->view->fetch('error');
        }
        Session::set('domainId',$id);
        Session::set('userId',$domain['user_id']);
        $this->assign('domain_type',$domain['domain_type']);
        $area = Db::name('Area')->where('pid',0)->column('id,name,level','id');
        $web = Web::where('domain_id',$id)->find();
        if(!empty($web['area'])){
            $web['area'] = explode(',',$web['area']);
        }
      
        $this->assign('info',$web);
        $this->assign('area',$area);
        return $this->view->fetch();
    }

    public function repassword(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $data['password'] || $this->error('修改密码必须填写');
            $data['repassword'] || $this->error('确认密码必须填写');
            if($data['password'] !== $data['repassword']){
                $this->error('密码必须和确认密码一致');
            }
            $data['password'] = md5(md5($data['password']) . Config::get('auth_key'));

            $result = model('User')->allowField(true)->save($data,['id'=>Session::get('spadminUser')['id']]);
            if($result === false){
                $this->error(model('User')->getError());
            }
            $this->success('操作成功');
        }
        $this->assign('username',Session::get('spadminUser')['username']);
        return $this->view->fetch();
    }
    public function logout(){
        Session::set('spaadminUser',null);
        Session::destroy();
        header('Location: '.url('login'));
        exit();

    }
}